import EmpVotingTestBed
import EmpVoting

from EmpVoting.PythonUtils import XmlSerializer

class RangeExperiment(object):
    
    def __init__(self, expConfigFilePath, replacableTagsToValuesDict):
        '''
        Constructor
        '''
        self.ExpConfigFilePath = expConfigFilePath
        self.ReplacableTagsToValuesDict = replacableTagsToValuesDict
        
    def Run(self):
        self.Serializer = XmlSerializer(rootModuleList=[EmpVotingTestBed, EmpVoting])
        
        configFile = open(self.ExpConfigFilePath)
        configAsStr = configFile.read()
        configFile.close()
        
        self.Serializer.ChangeCwdToContainingFolder(self.ExpConfigFilePath)
        flatConfigAsStr = self.Serializer.FlattenFileAttributes(configAsStr)
        
        self._RunRecursive(flatConfigAsStr, list(self.ReplacableTagsToValuesDict.items()))
        
        del self.__dict__["Serializer"]
        
    def _RunRecursive(self, expConfigString, remainingTagValuePairs):
        
        #Base Case
        if len(remainingTagValuePairs) == 0:
            experiment = self.Serializer.Deserialize(expConfigString)
            experiment.Run()

        else:
            curTagValuesPair = remainingTagValuePairs.pop()
            
            for value in curTagValuesPair[1]:
                curConfigStr = expConfigString.replace(curTagValuesPair[0], str(value))
                self._RunRecursive(curConfigStr, list(remainingTagValuePairs))
